package com.me.mygdxgame.models;


import com.badlogic.gdx.maps.objects.PolylineMapObject;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.ChainShape;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;

public class BoxBuilder {

	public final static float WORLD_TO_BOX = 0.02f;
	public final static float BOX_TO_WORLD = 50;
	
	public static Body CreateBoxBody(World world, BodyType bodyType, float posx, float posy, float width, float height,
		FixtureDef fixtureDef, Object userData, float density, float friction, float restitution) {
		BodyDef bodyDef = new BodyDef();
		bodyDef.type = bodyType;
		bodyDef.position.set(ConvertToBox(posx), ConvertToBox(posy));
		Body body = world.createBody(bodyDef);
		PolygonShape rec = new PolygonShape();
		rec.setAsBox(ConvertToBox(width / 2), ConvertToBox(height / 2));//, new Vector2(ConvertToBox(width / 2), ConvertToBox(height / 2)), 0f);
		fixtureDef.shape = rec;
		fixtureDef.density = density;
		fixtureDef.friction = friction;
		fixtureDef.restitution = restitution;
		body.createFixture(fixtureDef);
		body.setUserData(userData);
		rec.dispose();
		return body;
	}
	
	public static Body CreateGroundBody(World world, PolylineMapObject polyline) {
		Body groundbd;
		BodyDef bodydef = new BodyDef();
		bodydef.type = BodyType.StaticBody;
		float x = BoxBuilder.ConvertToBox(polyline.getPolyline().getX());
		float y = BoxBuilder.ConvertToBox(polyline.getPolyline().getY());
		bodydef.position.set(x, y);
		groundbd = world.createBody(bodydef);
		ChainShape chain = new ChainShape();
		float[] dinh = polyline.getPolyline().getVertices();
		float[] dinh2 = new float[dinh.length];
		for (int j = 0; j < dinh.length; j++) {
			dinh2[j] = BoxBuilder.ConvertToBox(dinh[j]);
		}
		chain.createChain(dinh2);
		FixtureDef fixtureDef = new FixtureDef();
		fixtureDef.shape = chain;
		fixtureDef.density = 0.0f;
//		fixtureDef.filter.categoryBits = CATEGORY_ENVIRONMENT;
//		fixtureDef.filter.maskBits = MASK_ENVIRONMENT;
		groundbd.createFixture(fixtureDef);
		chain.dispose();
		return groundbd;
	}
	
	public static Body CreateStoneBody(World world, float x, float y){
		BodyDef bodyDef = new BodyDef();
		bodyDef.type = BodyType.StaticBody;
		bodyDef.position.set(ConvertToBox(x), ConvertToBox(y));
		Body body = world.createBody(bodyDef);
		PolygonShape rect = new PolygonShape();
		rect.setAsBox(ConvertToBox(20), ConvertToBox(20));
		FixtureDef fixtureDef = new FixtureDef();
		fixtureDef.shape = rect;
		fixtureDef.density = 0.0f;
		body.createFixture(fixtureDef);
		rect.dispose();
		return body;
	}

	public static float ConvertToBox(float x) {
		return x * WORLD_TO_BOX;
	}
}
